# 安装mysql   redis   mysql
import subprocess, wget, os, shutil, tarfile, configparser


def shell_call(cmd):
    subprocess.run(cmd, shell=True)


def create_dir(dirname):
    if os.path.exists(dirname):
        shutil.rmtree(dirname)  # 删掉目录
    os.makedirs(dirname)


def download_mysql_tar(url, download_dir="/opt/install_file/"):
    # filename：/opt/install_file/mysql-8.0.17-el7-x86_64.tar.gz
    filename = os.path.join(download_dir, os.path.basename(url))
    if os.path.exists(filename):  # 存在
        print(f"{filename}安装文件下载成功！！！")
    else:
        print("开始下载安装文件......")
        create_dir(download_dir)
        wget.download(url, filename)
        print(f"{filename}文件下载完成!!!")
    return filename


def unpkg(tar_name, install_dir="/usr/local"):
    # basedir: /usr/local/mysql-8.0.17-el7-x86_64
    basedir = os.path.join(install_dir, os.path.basename(tar_name)[:-7])
    if os.path.exists(basedir):
        shutil.rmtree(basedir)
    print(f"安装{tar_name}开始解压到指定的目录：{install_dir}......")
    tar = tarfile.open(tar_name, mode="r:gz")
    tar.extractall(path=install_dir)
    tar.close()
    return basedir


def dir_link(src_dir, link_path):
    if os.path.basename(link_path):
        os.remove(link_path)
    os.symlink(src_dir, link_path)


# /usr/local/mysql-8.0.17-el7-x86_64/bin/mysqld --initialize --user=mysql --basedir=xxx --datadir=xxx
def init_command(basedir, datadir):
    bin_path = os.path.join(basedir, "bin/mysqld")  # /usr/local/mysql-8.0.17-el7-x86_64/bin/mysqld
    cmd = f"{bin_path} --initialize --user=mysql --basedir={basedir} --datadir={datadir}"
    return cmd


def config_init():
    print("开始配置my.cnf......")
    cf = configparser.ConfigParser(allow_no_value=True)
    cf.read("/etc/my.cnf")
    if not cf.has_section("mysqld"):  # 判断有没有指定的配置集  [mysqld]
        cf.add_section("mysqld")  # 添加 [mysqld] 配置集
    cf.set("mysqld", "basedir", "/usr/local/mysql-8.0.17-el7-x86_64")
    cf.set("mysqld", "datadir", "/usr/local/mysql/data")
    cf.set("mysqld", "port", "3306")
    cf.set("mysqld", "socket", "/tmp/mysql.sock")
    cf.set("mysqld", "pid-file", "/usr/local/mysql/data/mysql.pid")
    cf.set("mysqld", "log-error", "/usr/local/mysql/data/error.log")
    cf.set("mysqld", "character_set_server", "utf8")
    cf.set("mysqld", "user", "mysql")
    cf.set("mysqld", "skip-grant-tables")
    cf.set("mysqld", "max_connections", "500")
    cf.write(open("/etc/my.cnf", mode="w"))
    print("配置完成, 准备重启服务......")


# /usr/local/mysql-8.0.17-el7-x86_64/support-files/mysql.server
def command_init(basedir):
    mysql_bin = os.path.join(basedir, "support-files", "mysql.server")
    shutil.copy(mysql_bin, "/etc/init.d/mysqld")
    shell_call("/etc/init.d/mysqld restart")
    link_path = "/usr/local/bin/mysql"
    if os.path.exists(link_path):
        os.remove(link_path)
    os.symlink(os.path.join(basedir, "bin", "mysql"), link_path)


def main():
    url = "https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.17-el7-x86_64.tar.gz"
    link_path = "/usr/bin/mysql"  # 软连接路径，便于管理项目
    download_dir = "/opt/install_file/"  # 下载资源路径
    install_dir = "/usr/local"  # 安装路径
    data_dir = "/usr/local/mysql/data"  # 存放数据的目录

    # 1.创建mysql用户
    shell_call("groupadd mysql")
    shell_call("useradd -M mysql -g mysql -s /sbin/noligin")

    # 2.官网下载mysql的tar包到指定目录
    tar_name = download_mysql_tar(url, download_dir)

    # 3.解压tar到指定目录以及创建软连接
    basedir = unpkg(tar_name, install_dir)
    dir_link(basedir, link_path)  # 创建软连接
    create_dir(data_dir)  # 创建存储mysql服务数据的目录

    # 4.初始化mysql服务
    cmd = init_command(basedir, data_dir)
    print("MySQL服务初始化......")
    shell_call(cmd)
    print("MySQL服务初始化完毕!!!")

    # 5.初始化参数文件
    config_init()  # /etc/my.cnf

    # 6.配置启动命令
    command_init(basedir)
    print("恭喜！！！MySQL服务安装成功！！！")


if __name__ == '__main__':
    main()

# 1. 捋一遍整个自动部署mysql服务的代码，能看懂
# 2. 麻烦给位自己准备的红帽8的虚拟机当中，安装redis服务(单台)
